package com.sky.task;

import com.sky.constant.MessageConstant;
import com.sky.entity.Orders;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrdersMapper ordersMapper;

    /**
     * 处理超时订单
     */
    @Scheduled(cron = "0 * * * * ? ") // 每分钟执行一次
    public void processTimeoutOrder() {
        log.info("定时处理超时订单:{}", LocalDateTime.now());
        List<Orders> ordersTimeoutList = ordersMapper.getByStatusAndOrderTimeLT(Orders.PENDING_PAYMENT, LocalDateTime.now().minusMinutes(15));
        if (CollectionUtils.isNotEmpty(ordersTimeoutList)){
            List<Orders> ordersList = ordersTimeoutList.stream().peek(order -> {
                order.setStatus(Orders.CANCELLED);
                order.setCancelReason("订单支付超时，取消订单");
                order.setCancelTime(LocalDateTime.now());
            }).toList();
           Integer updateBatchOrderResult = ordersMapper.updateBatchOrder(ordersList);
           if (updateBatchOrderResult != ordersList.size()){
               throw new OrderBusinessException(MessageConstant.ORDER_TIMEOUT_CANCEL_FAILED);
           }
        }

    }

    @Scheduled(cron = "0 0 1 * * ?") // 每天凌晨一点钟执行
    public void processDeliveryOrder(){
        log.info("定时处理处于待派送状态的订单:{}",LocalDateTime.now());
        List<Orders> ordersDeliveryList = ordersMapper.getByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS, LocalDateTime.now().minusMinutes(60));
        if (CollectionUtils.isNotEmpty(ordersDeliveryList)){
            List<Orders> ordersList = ordersDeliveryList.stream().peek(order -> {
                order.setStatus(Orders.CANCELLED);
                order.setDeliveryTime(LocalDateTime.now());
            }).toList();
            Integer updateBatchOrderResult = ordersMapper.updateBatchOrder(ordersList);
            if (updateBatchOrderResult != ordersList.size()){
                throw new OrderBusinessException(MessageConstant.ORDER_TIMEOUT_CANCEL_FAILED);
            }
        }

    }

}
